import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart'; // 添加 url_launcher 导入

import '../../providers/product_provider.dart';
import '../../models/restaurant.dart';
import '../../models/product.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart';
import 'add_edit_product_screen.dart';
import '../product/product_template_screen.dart';
import '../product/categorized_template_screen.dart';
import 'package:flutter/services.dart'; // 用于Clipboard

class RestaurantDetailScreen extends StatefulWidget {
  final Restaurant restaurant;

  const RestaurantDetailScreen({
    super.key,
    required this.restaurant,
  });

  @override
  State<RestaurantDetailScreen> createState() => _RestaurantDetailScreenState();
}

class _RestaurantDetailScreenState extends State<RestaurantDetailScreen> {
  Map<int, bool> _selectedProducts = {};
  bool _isBatchMode = false;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      Provider.of<ProductProvider>(context, listen: false)
          .loadProductsByRestaurant(widget.restaurant.id!);
    });
  }

  @override
  void dispose() {
    Provider.of<ProductProvider>(context, listen: false).clearProducts();
    super.dispose();
  }

  
  // 复制电话号码到剪贴板
  void _copyPhoneNumber(String phone) {
    Clipboard.setData(ClipboardData(text: phone));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('已复制电话号码: $phone', style: const TextStyle(fontSize: 16)),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  // 拨打电话

// 拨打电话 - 使用 ACTION_DIAL 方案
Future<void> _makePhoneCall(String phoneNumber) async {
  // 1. 基础检查：确保号码不为空字符串
  if (phoneNumber.isEmpty) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('电话号码为空，无法拨打！', style: TextStyle(fontSize: 16)),
      ),
    );
    return;
  }

  // 2. 清理号码格式：只保留数字和+号，移除空格、横杠等
  final String cleanedNumber = phoneNumber.replaceAll(RegExp(r'[^\d+]'), '');
  print('清理后的号码: $cleanedNumber');

  // 3. 额外的格式检查
  if (cleanedNumber.isEmpty) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('电话号码格式无效，无法拨打！', style: TextStyle(fontSize: 16)),
      ),
    );
    return;
  }

  // 检查号码长度是否合理
  if (cleanedNumber.length < 3 || cleanedNumber.length > 15) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('电话号码长度异常: $cleanedNumber', style: const TextStyle(fontSize: 16)),
      ),
    );
    return;
  }

  // 4. 构建拨号的Uri，使用 Uri.parse 方法
  final Uri phoneUri = Uri.parse('tel:$cleanedNumber');
  print('构建的Uri: $phoneUri');

  // 5. 显示一个确认对话框，防止误触
  bool? userConfirmed = await showDialog<bool>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('确认拨号', style: TextStyle(fontSize: 20)),
        content: Text('即将为「${widget.restaurant.name}」拨打电话：\n$cleanedNumber', style: const TextStyle(fontSize: 18)),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消', style: TextStyle(fontSize: 18)),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('拨打', style: TextStyle(fontSize: 18, color: Colors.blue)),
          ),
        ],
      );
    },
  );

  // 如果用户点击了取消，则直接返回，不进行任何操作
  if (userConfirmed != true) {
    return;
  }

  // 6. 核心：尝试启动系统拨号界面
  try {
    // 检查设备是否能处理这个Uri
    if (await canLaunchUrl(phoneUri)) {
      // 如果可以，则启动拨号界面
      await launchUrl(phoneUri);
    } else {
      // 如果无法启动，尝试使用 intent 方式
      try {
        // 备用方案：使用 platform-specific code
        const methodChannel = MethodChannel('samples.flutter.dev/phone');
        await methodChannel.invokeMethod('dialPhone', {'number': cleanedNumber});
      } catch (e) {
        // 如果备用方案也失败，抛出异常
        throw '无法启动拨号界面，该设备可能不支持此操作。错误: $e';
      }
    }
  } catch (e) {
    // 7. 错误处理：捕获所有可能出现的异常并提示用户
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('拨号失败: $e', style: const TextStyle(fontSize: 16)),
        duration: const Duration(seconds: 3),
      ),
    );
  }
}

  // 批量操作相关方法
  void _toggleBatchMode() {
    setState(() {
      _isBatchMode = !_isBatchMode;
      if (!_isBatchMode) {
        _selectedProducts.clear();
      }
    });
  }

  void _toggleProductSelection(Product product) {
    setState(() {
      if (_selectedProducts.containsKey(product.id)) {
        _selectedProducts.remove(product.id);
      } else {
        _selectedProducts[product.id!] = true;
      }
    });
  }

  void _toggleSelectAll(List<Product> products) {
    setState(() {
      if (_selectedProducts.length == products.length) {
        _selectedProducts.clear();
      } else {
        _selectedProducts = {
          for (var product in products) product.id!: true
        };
      }
    });
  }

  Future<void> _batchDeleteProducts() async {
    final selectedProductIds = _selectedProducts.keys.toList();
    
    if (selectedProductIds.isEmpty) {
      SnackbarHelper.showError(context, '请至少选择一个商品');
      return;
    }

    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认删除', style: AppTheme.titleMedium),
        content: Text(
          '确定要删除选中的 ${selectedProductIds.length} 个商品吗？',
          style: AppTheme.bodyMedium,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消', style: AppTheme.bodyMedium),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(ctx).pop();
              await _performBatchDelete(selectedProductIds);
            },
            child: const Text('删除', style: TextStyle(fontSize: 18, color: Colors.red)),
          ),
        ],
      ),
    );
  }

  Future<void> _performBatchDelete(List<int> productIds) async {
    try {
      final provider = Provider.of<ProductProvider>(context, listen: false);
      int successCount = 0;
      
      for (var productId in productIds) {
        final success = await provider.deleteProduct(productId, widget.restaurant.id!);
        if (success) successCount++;
      }
      
      if (successCount > 0) {
        SnackbarHelper.showSuccess(context, '已删除 $successCount 个商品');
        setState(() {
          _isBatchMode = false;
          _selectedProducts.clear();
        });
        provider.loadProductsByRestaurant(widget.restaurant.id!);
      } else {
        SnackbarHelper.showError(context, '删除失败，请重试');
      }
    } catch (e) {
      SnackbarHelper.showError(context, '删除失败: ${e.toString()}');
    }
  }

  void _showDeleteDialog(BuildContext context, Product product) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认删除', style: AppTheme.titleMedium),
        content: Text(
          '确定要删除"${product.name}"吗？',
          style: AppTheme.bodyMedium,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消', style: AppTheme.bodyMedium),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(ctx).pop();
              await _deleteProduct(product);
            },
            child: const Text('删除', style: TextStyle(fontSize: 18, color: Colors.red)),
          ),
        ],
      ),
    );
  }

  Future<void> _deleteProduct(Product product) async {
    try {
      final provider = Provider.of<ProductProvider>(context, listen: false);
      final success = await provider.deleteProduct(product.id!, widget.restaurant.id!);
      
      if (success) {
        SnackbarHelper.showSuccess(context, '已删除"${product.name}"');
      } else {
        SnackbarHelper.showError(context, '删除失败，请重试');
      }
    } catch (e) {
      SnackbarHelper.showError(context, '删除失败: ${e.toString()}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '商品管理 - ${widget.restaurant.name}',
          style: AppTheme.titleLarge,
        ),
        actions: [
          if (_isBatchMode) ...[
            IconButton(
              icon: const Icon(Icons.delete),
              onPressed: _batchDeleteProducts,
              tooltip: '批量删除',
            ),
            IconButton(
              icon: const Icon(Icons.cancel),
              onPressed: _toggleBatchMode,
              tooltip: '取消批量选择',
            ),
          ] else ...[
            IconButton(
              icon: const Icon(Icons.library_books),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ProductTemplateScreen(
                      restaurantId: widget.restaurant.id!,
                    ),
                  ),
                ).then((result) {
                  if (result == true) {
                    Provider.of<ProductProvider>(context, listen: false)
                        .loadProductsByRestaurant(widget.restaurant.id!);
                  }
                });
              },
              tooltip: '从模板添加商品（旧版）',
            ),
            IconButton(
              icon: const Icon(Icons.category),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => CategorizedTemplateScreen(
                      restaurantId: widget.restaurant.id!,
                    ),
                  ),
                ).then((result) {
                  if (result == true) {
                    Provider.of<ProductProvider>(context, listen: false)
                        .loadProductsByRestaurant(widget.restaurant.id!);
                  }
                });
              },
              tooltip: '从分类模板添加商品',
            ),
            IconButton(
              icon: const Icon(Icons.checklist),
              onPressed: _toggleBatchMode,
              tooltip: '批量选择',
            ),
            IconButton(
              icon: const Icon(Icons.add),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => AddEditProductScreen(
                      restaurantId: widget.restaurant.id!,
                    ),
                  ),
                ).then((result) {
                  if (result == true) {
                    Provider.of<ProductProvider>(context, listen: false)
                        .loadProductsByRestaurant(widget.restaurant.id!);
                  }
                });
              },
            ),
          ],
        ],
      ),
      body: Column(
        children: [
          // 饭店信息卡片
          Container(
            width: double.infinity,
            margin: const EdgeInsets.all(12),
            padding: const EdgeInsets.all(20),
            decoration: AppTheme.infoCardDecoration,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  widget.restaurant.name,
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue[800],
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                if (widget.restaurant.contact != null && widget.restaurant.contact!.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.person, color: Colors.blue, size: 24),
                        const SizedBox(width: 8),
                        Text(
                          widget.restaurant.contact!,
                          style: AppTheme.bodyLarge,
                        ),
                      ],
                    ),
                  ),
                if (widget.restaurant.phone != null && widget.restaurant.phone!.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    child: InkWell(
                      onTap: () => _makePhoneCall(widget.restaurant.phone!), // 修正为调用 _makePhoneCall
                      onLongPress: () => _copyPhoneNumber(widget.restaurant.phone!),
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                        decoration: BoxDecoration(
                          color: Colors.green[50],
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: Colors.green),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const Icon(Icons.phone, color: Colors.green, size: 24),
                            const SizedBox(width: 8),
                            Text(
                              widget.restaurant.phone!,
                              style: const TextStyle(
                                fontSize: 18,
                                color: Colors.green,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(width: 8),
                            const Icon(Icons.arrow_forward, color: Colors.green, size: 20),
                          ],
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
          
          // 批量选择状态栏
          if (_isBatchMode)
            Container(
              padding: const EdgeInsets.all(12),
              color: Colors.blue[50],
              child: Row(
                children: [
                  Consumer<ProductProvider>(
                    builder: (context, productProvider, child) {
                      return Checkbox(
                        value: _selectedProducts.length == productProvider.products.length && 
                               productProvider.products.isNotEmpty,
                        onChanged: (value) => _toggleSelectAll(productProvider.products),
                      );
                    },
                  ),
                  Text(
                    '已选择 ${_selectedProducts.length} 个商品',
                    style: AppTheme.bodyLarge,
                  ),
                  const Spacer(),
                  TextButton(
                    onPressed: _batchDeleteProducts,
                    child: const Text(
                      '批量删除',
                      style: TextStyle(color: Colors.red),
                    ),
                  ),
                ],
              ),
            ),
          
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: Text(
              '商品列表',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
          ),
          const SizedBox(height: 8),
          
          // 商品列表
          Expanded(
            child: Consumer<ProductProvider>(
              builder: (context, productProvider, child) {
                if (productProvider.isLoading) {
                  return const Center(child: CircularProgressIndicator());
                }
                
                if (productProvider.products.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '暂无商品',
                          style: AppTheme.bodyLarge,
                          textAlign: TextAlign.center,
                        ),
                        const SizedBox(height: 16),
                        ElevatedButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => CategorizedTemplateScreen(
                                  restaurantId: widget.restaurant.id!,
                                ),
                              ),
                            ).then((result) {
                              if (result == true) {
                                Provider.of<ProductProvider>(context, listen: false)
                                    .loadProductsByRestaurant(widget.restaurant.id!);
                              }
                            });
                          },
                          child: const Text('从模板快速添加商品'),
                        ),
                      ],
                    ),
                  );
                }

                return ListView.builder(
                  itemCount: productProvider.products.length,
                  itemBuilder: (context, index) {
                    final product = productProvider.products[index];
                    final isSelected = _selectedProducts.containsKey(product.id);
                    
                    return Card(
                      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      color: isSelected ? Colors.blue[50] : null,
                      child: ListTile(
                        contentPadding: const EdgeInsets.all(16),
                        leading: _isBatchMode
                            ? Checkbox(
                                value: isSelected,
                                onChanged: (value) => _toggleProductSelection(product),
                              )
                            : null,
                        title: Text(
                          product.name,
                          style: AppTheme.bodyLarge,
                        ),
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const SizedBox(height: 4),
                            Text(
                              '规格: ${product.spec}',
                              style: AppTheme.bodyMedium,
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '单价: ¥${product.currentPrice.toStringAsFixed(2)}',
                              style: const TextStyle(
                                fontSize: 18,
                                color: Colors.green,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                        trailing: _isBatchMode
                            ? null
                            : SizedBox(
                                width: 120,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    // 编辑按钮
                                    IconButton(
                                      icon: const Icon(Icons.edit, color: Colors.blue),
                                      onPressed: () {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => AddEditProductScreen(
                                              restaurantId: widget.restaurant.id!,
                                              product: product,
                                            ),
                                          ),
                                        ).then((result) {
                                          if (result == true) {
                                            Provider.of<ProductProvider>(context, listen: false)
                                                .loadProductsByRestaurant(widget.restaurant.id!);
                                          }
                                        });
                                      },
                                    ),
                                    // 删除按钮
                                    IconButton(
                                      icon: const Icon(Icons.delete, color: Colors.red),
                                      onPressed: () => _showDeleteDialog(context, product),
                                    ),
                                  ],
                                ),
                              ),
                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}